package com.sciology.xpathutility.contentassist;

public class CompletionTriggerWord extends AbstractCompletionTrigger {

  public final static String INSTANCE_QNAME = "wordtrigger";
  public final static String WORD_ATTRIBUTE_QNAME = "word";
  private final String word;
  private final String extension;
  private final String plainProposal;

  /**
   * @param p_word
   */
  public CompletionTriggerWord(String p_word, String p_extendWith, String p_plainProposal) {
    this.word = p_word;
    this.extension = p_extendWith;
    this.plainProposal = p_plainProposal;
  }

  
  String getWord() {
    return this.word;
  }
  
  String getPlainProposal() {
    return this.plainProposal;
  }
  
  String getExtension() {
    return this.extension;
  }
    
  public boolean isMatchFor(String text) {
    for (int i=0; i<this.word.length(); i++) {
      if (text.endsWith(this.word.substring(0,this.word.length()-i))) {
        return true;
      }
    }
    return false;
  }

  public String getInsertString(String text) {
    String wordRemainder = null;
    for (int i=0; i<this.word.length(); i++) {
      if (text.endsWith(this.word.substring(0,this.word.length()-i))) {
        wordRemainder = this.word.substring(this.word.length()-i);
        break;
      }
    }
    return wordRemainder+this.extension;
  }

  public String getInsertString() {
    return this.getInsertString(this.text);
  }

  public int compareTo(AbstractCompletionTrigger p_other) {
    // Always prefer WordCompletions unless the standard proposal starts with a \ and only wants to add one character
    if (p_other instanceof CompletionTriggerExpression) {
      return -1;
    } else {
      // The more we can use, the better...
      int thisLength = this.getInsertString().length();
      int otherLength = p_other.getInsertString().length();
      int thisPresent = thisLength+1-this.getWord().length();
      int otherPresent = otherLength+1-((CompletionTriggerWord)p_other).getWord().length();
      if (thisPresent < otherPresent) {
        return -1;
      } else if (thisPresent == otherPresent) {
        if (thisLength < otherLength) {
          return -1;
        } else {
          return +1;
        }
      } else {
        return +1;
      }
    }
  }
}
